package com.sto.stoapp.db.manager;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.db.constant.UserConstant;
import com.sto.stoapp.http.response.download.info.UserInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserManager extends StoDataBase implements DownLoadDao<UserInfo> {

	static UserManager mgr;

	public static UserManager getInstance(Context context) {
		if (mgr == null)
			mgr = new UserManager(context);
		return mgr;
	}

	private UserManager(Context context) {
		super(context);
	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(UserConstant.USER_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}

	@Override
	public void insertOrReplace(List<UserInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (UserInfo info : datas) {
					if ("USER_RULE".equals(info.type)) {
						ContentValues values = buildContentValues(info);
						if (replace(values)) {
							Log.d("插入一条离线基本信息", "成功");
						} else {
							Log.d("插入一条离线基本信息", "失败");
							// }
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(UserConstant.USER_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(UserConstant.USER_TABLE, STATUS + "=?",
						new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(UserConstant.USER_TABLE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public ContentValues buildContentValues(UserInfo entity) {
		ContentValues values = new ContentValues();

		values.put(UserConstant.KEY, entity.key);
		values.put(UserConstant.TYPE, entity.type);
		values.put(UserConstant.VERSION, entity.version);
		values.put(UserConstant.BACKUP1, entity.backup1);
		values.put(UserConstant.ID, entity.id);
		values.put(UserConstant.STATUS, entity.status);
		values.put(UserConstant.ROLE, entity.value);

		return values;
	}

	/**
	 * 查询角色
	 * 
	 * @param siteCode
	 * @param passWord
	 * @return
	 */
	public ArrayList<String> queryRoleByPw(String site, String jobNumber) {
		SQLiteDatabase qb = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
		Cursor c = qb.query(UserConstant.USER_TABLE,
				new String[] { UserConstant.ROLE }, UserConstant.KEY + "=?  ",
				new String[] { site + jobNumber }, null, null, null);
		String role = "";
		if (c != null && c.moveToNext()) {
			role = c.getString(c.getColumnIndex(UserConstant.ROLE));
		}
		closeCursor(c);
		closeDb(UnifiedStaticType.READ_DATABASE);

		if (role.trim().length() == 0)
			return null;
		String[] roleStrs = role.replace("[", "").replace("]", "").split(",");

		return new ArrayList<String>(Arrays.asList(roleStrs));
	}
}
